<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="view-account-top-logo">
          <img :src="chatgpt" alt="" /> <span>Tunnel ChatBox</span>
        </div>
      </div>
      <n-tabs
        default-value="denglu"
        size="large"
        ref="tabsInstRef"
        animated
        v-model:value="valueRef"
        style="margin: 0 -4px"
        justify-content="space-evenly"
        pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;"
      >
        <n-tab-pane name="denglu" tab="登录">
          <div class="view-account-form">
            <n-form
              ref="formRef"
              label-placement="left"
              size="large"
              :model="formInline"
              :rules="rules"
            >
              <n-form-item path="username">
                <n-input
                  v-model:value="formInline.username"
                  placeholder="请输入用户名"
                >
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <PersonOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="password">
                <n-input
                  v-model:value="formInline.password"
                  type="password"
                  showPasswordOn="click"
                  placeholder="请输入密码"
                >
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <LockClosedOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="verificationCode">
                <n-grid cols="2" x-gap="2">
                  <n-grid-item>
                    <n-input
                      v-model:value="formInline.verificationCode"
                      placeholder="请输入验证码"
                    >
                    </n-input>
                  </n-grid-item>
                  <n-grid-item style="cursor: pointer;">
                    <img
                      :src="base64Image"
                      alt=""
                      style="height: 40px; width: 100%"
                      @click="oninit"
                    />
                  </n-grid-item>
                </n-grid>
              </n-form-item>
              <n-form-item>
                <n-button
                  type="primary"
                  @click="handleSubmit"
                  size="large"
                  :loading="loading"
                  block
                >
                  登录
                </n-button>
              </n-form-item>
              <n-form-item class="default-color">
                <div class="flex view-account-other">
                  <div
                    class="flex-initial"
                    style="margin-left: auto; color: #1f6feb"
                    @click="handleZhuce"
                  >
                    <a href="javascript:">注册账号</a>
                  </div>
                </div>
              </n-form-item>
            </n-form>
          </div>
        </n-tab-pane>
        <n-tab-pane name="zhuce" tab="注册">
          <div class="view-account-form">
            <n-form
              ref="zhuceRef"
              label-placement="left"
              size="large"
              :model="zhuceForm"
              :rules="rules"
            >
              <n-form-item path="username">
                <n-input
                  v-model:value="zhuceForm.username"
                  placeholder="请输入用户名"
                >
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <PersonOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="password">
                <n-input
                  v-model:value="zhuceForm.password"
                  type="password"
                  showPasswordOn="click"
                  placeholder="请输入密码"
                >
                  <template #prefix>
                    <n-icon size="18" color="#808695">
                      <LockClosedOutline />
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="verificationCode">
                <n-grid cols="2" x-gap="2">
                  <n-grid-item>
                    <n-input
                      v-model:value="zhuceForm.verificationCode"
                      placeholder="请输入验证码"
                    >
                    </n-input>
                  </n-grid-item>
                  <n-grid-item style="cursor: pointer;">
                    <img
                      :src="base64Image"
                      alt=""
                      style="height: 40px; width: 100%"
                      @click="oninit"
                    />
                  </n-grid-item>
                </n-grid>
              </n-form-item>
              <n-form-item>
                <n-button
                  type="primary"
                  size="large"
                  :loading="loading"
                  block
                  @click="submitzhuce"
                >
                  立即注册
                </n-button>
              </n-form-item>
            </n-form>
          </div>
        </n-tab-pane>
      </n-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";

import {
  useMessage,
  NForm,
  NFormItem,
  NButton,
  NInput,
  NIcon,
  NGrid,
  NGridItem,
  NTabs,
  NTabPane,
} from "naive-ui";
import chatgpt from "@/assets/images/chat.png";
import { getCode, register,login} from "@/api";

import {
  PersonOutline,
  LockClosedOutline,
  LogoGithub,
  LogoFacebook,
} from "@vicons/ionicons5";
import { TabsInst } from "naive-ui";

const formRef = ref();
const zhuceRef = ref();
const tabsInstRef = ref<TabsInst | null>(null);
const message = useMessage();
const loading = ref(false);

const formInline = reactive({
  username: "",
  password: "",
  verificationCode: "",
  codeKey: "",
});

let zhuceForm = reactive({
  username: "",
  password: "",
  verificationCode: "",
  codeKey: "",
});
const base64Image = ref("");

const rules = {
  username: { required: true, message: "请输入用户名", trigger: "blur" },
  password: { required: true, message: "请输入密码", trigger: "blur" },
  verificationCode: { required: true, message: "请输入验证码", trigger: "blur" },
};

const valueRef = ref("denglu");
const handleZhuce = () => {
  valueRef.value = "zhuce";
  nextTick(() => tabsInstRef.value?.syncBarPosition());
};

const submitzhuce = (e) => {
  e.preventDefault();
  zhuceRef.value.validate(async (errors) => {
    if (!errors) {
      const { username, password, verificationCode, codeKey } = zhuceForm;
      loading.value = true;
      const params = {
        username,
        password,
        verificationCode,
        codeKey,
      };
      try {
        const { data, state } = await register(params);
        if (state.code === "0") {
          message.success("注册成功,您的用户名为" + data.username);
          valueRef.value = "denglu";
          nextTick(() => tabsInstRef.value?.syncBarPosition());
        }else{
          message.error(state.msg);
        }
      } finally {
        zhuceForm.password=''
        zhuceForm.username=''
        loading.value = false;
        message.destroyAll();
        oninit()
      }
    }
  });
};

const router = useRouter();

const handleSubmit = (e) => {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const { username, password, verificationCode, codeKey } = formInline;
      message.loading('登录中...');
      loading.value = true;
      const params = {
        username,
        password,
        verificationCode,
        codeKey
      };
      try {
        const { data, state } = await login(params);
        message.destroyAll();

        if (state.code == '0') {
          localStorage.setItem('token',data.token)
          localStorage.setItem('username',data.username)
          message.success('登录成功，即将进入系统');
            router.replace('/');
        } else {
					localStorage.setItem('token','')
					localStorage.setItem('username','')
          message.warning(state.msg || '登录失败');
        }
      } finally {
        loading.value = false;
      }
    } else {
      message.error('请填写完整信息，并且进行验证码校验');
    }
  });
};


async function oninit() {
  try {
    const { data } = await getCode();
    base64Image.value = "data:image/png;base64," + data.base64Image;
    formInline.codeKey = data.codeKey;
    zhuceForm.codeKey = data.codeKey;
  } catch (error) {
    console.log(error);
  } finally {
  }
}

onMounted(() => {
  oninit();
});
</script>

<style lang="less" scoped>
.view-account {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;

  &-container {
    flex: 1;
    padding: 32px 12px;
    max-width: 384px;
    min-width: 320px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  &-top {
    padding: 32px 0;
    text-align: center;
    &-logo {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 2rem;
      font-weight: 600;
      & img {
        width: 4rem;
        height: auto;
        margin-right: 0.3rem;
      }
    }

    &-desc {
      font-size: 14px;
      color: #808695;
    }
  }

  &-other {
    width: 100%;
  }

  .default-color {
    color: #515a6e;

    .ant-checkbox-wrapper {
      color: #515a6e;
    }
  }
}

@media (min-width: 768px) {
  .view-account {
    background-image: url("../../assets/images/login.svg");
    background-repeat: no-repeat;
    background-position: 50%;
    background-size: 100%;
  }

  .page-account-container {
    padding: 32px 0 24px 0;
  }
}
</style>
